import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:hxdj/common/base_page/base_page.dart';
import 'package:hxdj/common/dio/dio_http.dart';
import 'package:hxdj/common/my_constant.dart';
import 'package:hxdj/common/my_global.dart';
import 'package:hxdj/home/address/select_address/address_model.dart';
import 'package:hxdj/home/locationManager/location_manager.dart';
import 'package:hxdj/home/order/order_model.dart';
import 'package:hxdj/login/user_model.dart';
import 'package:hxdj/recommend_project/recommend_project_viewmodel.dart';
import 'package:provider/provider.dart';

class HomeViewModel extends BaseViewModel {
  //询问权限
  bool isPermission = false;

  LocationManager locationManager = LocationManager();

  //当前位置信息省份
  String? addressCity;

  AddressModel? addressModel;

  late List<OrderModel> orderModels = [];

  //真实技师
  late NearbyTechnicianModel? technicianModel;

  //推荐项目
  late ProjectModel? projectModel;

  //询问权限
  Future<bool> requestPermission() async {
    setState(ViewState.loading);
    // 请求权限
    isPermission = await locationManager.requestPermission();
    if (!isPermission) {
      //定位失败, 更新页面.
      setState(ViewState.error);
    } else {
      locationManager.getCurrentLocation((Map<String, dynamic> result) {
        if (result.isNotEmpty) {
          addressCity = result['city'];
          debugPrint('接收到的定位信息: $result');

          requetsHomeData();
        }
      }).catchError((err) {
        // Fluttertoast.showToast(msg: err);
        setState(ViewState.error);
      });
    }
    return isPermission;
  }

  //请求首页的相关数据.
  requetsHomeData({bool isRefresh = false}) async {
    // 请求首页的相关数据.
    List<dynamic> results;
    if (!isRefresh) {
      setState(ViewState.loading);
      // 请求默认地址. //请求附近的真是技师.
      results = await Future.wait(
          [requestNearbyTechnicianModel(), requestMoreProject(), requestRecentOrderModel(), requestAddress()]);
    } else {
      results = await Future.wait([requestNearbyTechnicianModel(), requestMoreProject(), requestRecentOrderModel()]);
    }

    // 请求附近的真是技师.
    Map<String, dynamic> resultTechnician = results[0];
    if (resultTechnician['code'] == 0) {
      try {
        List<dynamic> technicianDataList = resultTechnician['data'];
        technicianModel = NearbyTechnicianModel.fromMap(technicianDataList.first);
      } catch (e) {
        technicianModel = NearbyTechnicianModel.fromMap({});
      }
    }

    Map<String, dynamic> resultProject = results[1];
    projectModel = ProjectModel.fromMap({});
    if (resultProject['code'] == 0) {
      List<dynamic> projectList = resultProject["data"] ?? [];
      if (projectList.isNotEmpty) {
        projectModel = ProjectModel.fromMap(projectList.first);
      }
    }
    Map<String, dynamic> resultOrderMap = results[2];
    if (resultOrderMap['code'] == 0) {
      orderModels.clear();

      Map<String, dynamic> dataMap = resultOrderMap["data"];

      List<dynamic> projectOrderList = dataMap["list"] ?? [];

      for (var element in projectOrderList) {
        OrderModel orderModel = OrderModel.fromMap(element);
        orderModels.add(orderModel);
      }
    }
    if (results.length > 3) {
      Map<String, dynamic> resultAddress = results[3];
      if (resultAddress['code'] == 0) {
        List<dynamic> addressDataList = resultAddress['data']['list'] ?? [{}];
        for (Map<String, dynamic> element in addressDataList) {
          //是否是默认地址 1：默认地址 2：不是
          if (element['default_status'] == 1) {
            addressModel = AddressModel.fromMap(element);
          }
        }
        if (addressDataList.isNotEmpty) {
          addressModel = AddressModel.fromMap(addressDataList.first);
        }
      }
    }

    // 请求成功后, 更新页面.
    setState(ViewState.normal);

    //请求预约页面的相关数据
    RecommendProjectViewModel projectViewModel = Provider.of<RecommendProjectViewModel>(context, listen: false);
    projectViewModel.requestData(isFresh: true);
    if (!isRefresh) {
      requestMemberInfo();

      getStandardList();
    }
  }

  //选择了其他地址
  setAddress(AddressModel? tempAddressModel) {
    addressModel = tempAddressModel;
    notifyListeners();
  }

  //请求默认地址
  Future<Map<String, dynamic>> requestAddress() async {
    return await DioHttpManager().request(MyApi.memberAdds, method: DioHttpManager.post);
  }

  //获取更多项目
  Future<Map<String, dynamic>> requestMoreProject() async {
    return await DioHttpManager().request(MyApi.getShopRecommentObject,
        method: DioHttpManager.post, data: {"min_price": "98", "max_price": "998", "limit": "4"});
  }

  //请求附近的真是技师
  Future<Map<String, dynamic>> requestNearbyTechnicianModel() async {
    return await DioHttpManager()
        .request(MyApi.getNearbyRealTechnicianList, method: DioHttpManager.post, data: {"page": "1", "limit": "2"});
  }

  //请求最近的订单
  Future<Map<String, dynamic>> requestRecentOrderModel() async {
    return await DioHttpManager().request(MyApi.anmoV2OrderList,
        method: DioHttpManager.post,
        data: {"page": "1", "limit": MyConstant.pageSize, "member_type": "0", "order_status": "2"});
  }

  //技师入住二维码
  Future<String> requestTechnicianCheckIn() async {
    Map<String, dynamic> resultMap = await DioHttpManager().request(MyApi.getTipList, method: DioHttpManager.post);
    if (resultMap['code'] == 0) {
      try {
        Map<String, dynamic> dataMap = resultMap["data"]["list"]["open_tip"];
        String settleKefuQrcode = dataMap["settle_kefu_qrcode"]["value"];
        return settleKefuQrcode;
      } catch (e) {
        return "";
      }
    }
    return "";
  }

  //刷新订单, 不用全部数据都刷新
  reloadOrderData() async {
    Map<String, dynamic> resultOrderMap = await requestRecentOrderModel();
    if (resultOrderMap['code'] == 0) {
      orderModels.clear();

      Map<String, dynamic> dataMap = resultOrderMap["data"];

      List<dynamic> projectOrderList = dataMap["list"] ?? [];

      for (var element in projectOrderList) {
        OrderModel orderModel = OrderModel.fromMap(element);
        orderModels.add(orderModel);
      }
    }
    notifyListeners();
  }

  ///开始定位
  Future<void> startLocation() async {
    locationManager.startLocation();
  }

  //用户信息member_info
  Future<Map<String, dynamic>> requestMemberInfo() async {
    Map<String, dynamic> resultMap = await DioHttpManager().request(MyApi.memberInfo, method: DioHttpManager.post);
    UserDetailModel userDetailModel = UserDetailModel.fromMap(resultMap);
    MyGlobalViewModel globalViewModel = MyGlobalViewModel.getGlobalViewModel(context);
    globalViewModel.updateUserInfo(userDetailModel);
    return resultMap;
  }

  //获取公共的参数
  Future<Map<String, dynamic>> getStandardList() async {
    Map<String, dynamic> resultMap = await DioHttpManager().request(MyApi.getStandardList, method: DioHttpManager.post);

    StandardDetailModel standardDetailModel = StandardDetailModel.fromMap(resultMap["data"]);
    MyGlobalViewModel globalViewModel = MyGlobalViewModel.getGlobalViewModel(context);
    globalViewModel.standardDetailModel = standardDetailModel;

    return resultMap;
  }
}

class NearbyTechnicianModel {
  final int? isFalse;
  final int? tId;
  final int? mId;
  final String? imgs;
  final double? distance;
  final int? id;
  final int? dataType;
  final String? distanceStr;
  final String? name;
  final String? logo;
  final int? sex;
  final String? desc;
  final int? orderQuantity;
  final int? dateType;
  final String? aboutDate;
  final int? yeaOrderNum;

  NearbyTechnicianModel({
    this.isFalse,
    this.tId,
    this.mId,
    this.imgs,
    this.distance,
    this.id,
    this.dataType,
    this.distanceStr,
    this.name,
    this.logo,
    this.sex,
    this.desc,
    this.orderQuantity,
    this.dateType,
    this.aboutDate,
    this.yeaOrderNum,

  });

  factory NearbyTechnicianModel.fromJson(String str) => NearbyTechnicianModel.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory NearbyTechnicianModel.fromMap(Map<String, dynamic> json) => NearbyTechnicianModel(
        isFalse: json["is_false"],
        tId: json["t_id"],
        mId: json["m_id"],
        imgs: json["imgs"],
        distance: json["distance"]?.toDouble(),
        id: json["id"],
        dataType: json["data_type"],
        distanceStr: json["distance_str"],
        name: json["name"],
        logo: json["logo"],
        sex: json["sex"],
        desc: json["desc"],
        orderQuantity: json["order_quantity"],
        dateType: json["date_type"],
        aboutDate: json["about_date"],
        yeaOrderNum: json["year_order_num"],

      );

  Map<String, dynamic> toMap() => {
        "is_false": isFalse,
        "t_id": tId,
        "m_id": mId,
        "imgs": imgs,
        "distance": distance,
        "id": id,
        "data_type": dataType,
        "distance_str": distanceStr,
        "name": name,
        "logo": logo,
        "sex": sex,
        "desc": desc,
        "order_quantity": orderQuantity,
        "date_type": dateType,
        "about_date": aboutDate,
        "year_order_num": yeaOrderNum,
      };
}
